import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { setToken, getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { MessageBox } from 'element-ui'
import { refreshToken, getInit } from '@/api/user'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next()
      NProgress.done()
    } else {
      if (!sessionStorage.getItem('refreshToken')) {
        sessionStorage.setItem('refreshToken', true)
        console.log(456)
        refreshToken().then(res => {
          if (res.data.code === 200) {
            setToken(res.data.data.auth.token)
            next()
          }
        }).catch(() => {
          MessageBox.confirm('身份验证已过期或失败，请重新登录', '提示', {
            confirmButtonText: '去登录',
            showCancelButton: false,
            type: 'error',
            callback: () => {
              return next('/login')
            }
          })
        })
        getInit().then((res) => {
          console.log(123456, 'init')
          localStorage.setItem('init', JSON.stringify(res.data.data))
        })
      }
      next()
      const roles = []
      // 存在 token 即为已登录，放行
      const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
      // dynamically add accessible routes
      router.addRoutes(accessRoutes)
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
